﻿/****************************************************************
*   作者：Morain
*   创建时间：2018/2/25 17:18:40
*   描述说明：
*****************************************************************/
using System;
using System.Collections.Generic;
using System.Text;

namespace Model
{
  [ObjectSystem]
  public class OpcodeTypeComponentSystem : ObjectSystem<OpcodeTypeComponent>, IAwake
  {
    public void Awake()
    {
      Get().Load();
    }
  }
  public class OpcodeTypeComponent : Component
  {
    public Dictionary<ushort, Type> OpcodeType { get; set; }
    public Dictionary<Type, MessageAttribute> MessageOpcode { get; set; }

    public void Load()
    {
      this.OpcodeType = new Dictionary<ushort, Type>();
      this.MessageOpcode = new Dictionary<Type, MessageAttribute>();

      Type[] types = DllHelper.GetAll();

      foreach (Type type in types)
      {
        object[] attrs = type.GetCustomAttributes(typeof(MessageAttribute), false);
        if (attrs.Length == 0) continue;

        MessageAttribute messageAttribute = (MessageAttribute)attrs[0];
        this.MessageOpcode[type] = messageAttribute;
        this.OpcodeType[messageAttribute.Opcode] = type;
      }
    }

    public ushort GetOpcode(Type type)
    {
      if (!this.MessageOpcode.TryGetValue(type, out MessageAttribute messageAttribute))
      {
        throw new Exception($"查找Opcode失败！{type}");
      }
      return messageAttribute.Opcode;
    }

    public Type GetType(ushort opcode)
    {
      if (!this.OpcodeType.TryGetValue(opcode, out Type type))
      {
        throw new Exception($"查找Type失败！{opcode}");
      }
      return type;
    }

    public override void Dispose()
    {
      if (this.Id == 0)
      {
        return;
      }
      base.Dispose();
    }
  }
}
